package com.pks.autoInsurance.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.pks.autoInsurance.dto.LoginDto;

public class LoginDAOImpl extends AutoInsuranceDAO implements LoginDAO {
	/*
	 * Performs login authentication and authorisation for the user.
	 * 
	 * @see
	 * com.cts.autoInsurance.dao.LoginDAO#authenticateUser(com.cts.autoInsurance
	 * .dto.LoginDto)
	 */
	@Override
	public int authenticateUser(LoginDto loginReq) {
		System.out.println(getClass() + "::::authenticateUser::::begin");
		Connection connection = getConnection();
		String sql = "SELECT USER_ID,PASSWD FROM USERS_LOGIN WHERE USER_ID=? AND PASSWD=?";
		try {
			connection.setAutoCommit(false);
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, loginReq.getUserId());
			preparedStatement.setString(2, loginReq.getPasswd());
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				if (resultSet.getString("USER_ID").equalsIgnoreCase(
						"adminadmin")) {
					return VALID_ADMIN;
				}
				return VALID_USER;
			}

		} catch (SQLException e) {

			System.err.println(getClass() + "::::" + e.getMessage());
			return INVALID_USER;
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				System.err.println(getClass() + "::::" + e.getMessage());
			}
		}
		System.out.println(getClass() + "::::authenticateUser::::end");
		return INVALID_USER;
	}

}
